<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="cartInfo in cartInfoList"
          :key="cartInfo.id"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              :checked="!!cartInfo.isChecked"
              name="chk_list"
              @change="checkCartInfoState(cartInfo)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">
              {{ cartInfo.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="changeSkuNum('decrement', cartInfo)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="cartInfo.skuNum"
              minnum="1"
              class="itxt"
              @change="changeSkuNum('change', cartInfo, $event)"
            />
            <a
              href="javascript:void(0)"
              class="plus"
              @click="changeSkuNum('increment', cartInfo)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:;"
              class="sindelet"
              @click="showDialogByDelOneCartInfo(cartInfo)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#none" @click="showDialogByDelSelectCartInfo"
          >删除选中的商品</a
        >
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ selectCount }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectedMoney }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
    <Dialog :visible.sync="isShow">
      <template v-slot:header>
        <h3>提示</h3>
      </template>
      <template>
        <p class="dialog-body">真的要删除此条数据吗？</p>
      </template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn" @click="isShow = false">取消</button>
          <button class="btn btn-primary" @click="delCartInfo">确认</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqShopCartListData,
  reqChangeShopCartInfoState,
  reqUpdateAllShopCartInfoState,
  reqDelOneShopCartInfo,
  reqDelSelectCartInfo,
  reqAddOrUpdateCart,
} from '@/api'
import { skuNumReg } from '@/utils/reg'
import _ from 'lodash'
export default {
  name: 'ShopCart',
  data() {
    return {
      cartInfoList: [],
      isShow: false,
      skuId: '',
      isDelOne: false,
      skuIdList: [], //选中商品的id
      leftCartListInfo: [], //剩余商品
      timeId: '',
      num: 0, //初始修改量
    }
  },
  computed: {
    // 全选按钮
    checkAll: {
      get() {
        return (
          this.cartInfoList.length &&
          this.cartInfoList.every((cartInfo) => cartInfo.isChecked === 1)
        )
      },
      async set(val) {
        // 只要一更改，就会执行这里面的代码
        let isChecked = val ? 1 : 0
        let skuIdList = []
        this.cartInfoList.forEach((cartInfo) => {
          cartInfo.isChecked = isChecked
          // this.checkCartInfoState({
          //   skuId: cartInfo.skuId,
          //   isChecked: 1 - isChecked,
          // })
          skuIdList.push(cartInfo.skuId)
        })
        if (!skuIdList.length) return
        const res = await reqUpdateAllShopCartInfoState(skuIdList, isChecked)
        if (res.code === 200) {
          alert('更新成功！')
        } else {
          alert('更新失败')
        }
      },
    },
    // 已选择商品总数
    selectCount() {
      // return this.cartInfoList.reduce((pre, current) => {
      //   return pre + current.isChecked
      // }, 0)
      return this.cartInfoList.reduce(
        (pre, current) => pre + current.isChecked,
        0
      )
    },
    //计算购物车选中商品的总金额
    selectedMoney() {
      return this.cartInfoList.reduce(
        (pre, current) =>
          pre + current.isChecked * current.skuPrice * current.skuNum,
        0
      )
    },
  },
  methods: {
    // 修改购物车商品数量
    // changeSkuNum: _.debounce(async function (type, cartInfo, e) {
    //   let num = 0 //定义初始改变值
    //   switch (type) {
    //     case 'increment':
    //       if (cartInfo.skuNum < 200) {
    //         cartInfo.skuNum++
    //         num++
    //       }
    //       break
    //     case 'decrement':
    //       if (cartInfo.skuNum > 1) {
    //         cartInfo.skuNum--
    //         num--
    //       }
    //       break
    //     case 'change':
    //       // 输入的数量
    //       let newNum = e.target.value
    //       // 保存原始数量
    //       const originNum = cartInfo.skuNum
    //       if (skuNumReg.test(newNum)) {
    //         num = newNum - cartInfo.skuNum
    //         cartInfo.skuNum = newNum
    //         // 输入值大于200时
    //         if (newNum > 200) {
    //           newNum = 200
    //           num = newNum - cartInfo.skuNum
    //           cartInfo.skuNum = newNum
    //         }
    //       } else {
    //         e.target.value = originNum
    //       }
    //       break
    //   }
    //   if (num === 0) return // 如果num=0的话，说明数量没有变化，不需要再发送请求
    //   await reqAddOrUpdateCart(cartInfo.skuId, num)
    // }, 500),
    // 修改购物车商品数量
    async changeSkuNum(type, cartInfo, e) {
      if (this.timeId) clearTimeout(this.timeId)
      // let num = 0 //定义初始改变值
      switch (type) {
        case 'increment':
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++
            this.num++
          }
          break
        case 'decrement':
          if (cartInfo.skuNum > 1) {
            cartInfo.skuNum--
            this.num--
          }
          break
        case 'change':
          // 输入的数量
          let newNum = e.target.value
          // 保存原始数量
          const originNum = cartInfo.skuNum
          if (skuNumReg.test(newNum)) {
            this.num = newNum - cartInfo.skuNum
            cartInfo.skuNum = newNum
            // 输入值大于200时
            if (newNum > 200) {
              newNum = 200
              this.num = newNum - cartInfo.skuNum
              cartInfo.skuNum = newNum
            }
          } else {
            e.target.value = originNum
          }
          break
      }
      if (this.num === 0) return // 如果num=0的话，说明数量没有变化，不需要再发送请求
      // await reqAddOrUpdateCart(cartInfo.skuId, num)
      this.timeId = setTimeout(async () => {
        const res = await reqAddOrUpdateCart(cartInfo.skuId, this.num)
        if (res.code === 200) {
          this.num = 0
        }
      }, 500)
      // await reqAddOrUpdateCart(cartInfo.skuId, num)
    },
    // 获取购物车数据
    async getCartListData() {
      const res = await reqShopCartListData()
      if (res.code === 200) {
        this.cartInfoList = res.data[0] ? res.data[0].cartInfoList : []
      } else {
        console.log(res.message)
      }
    },
    // 点击删除显示模态框并一个存储商品ID
    showDialogByDelOneCartInfo(cartInfo) {
      // 模态框显示
      this.isShow = true
      // 存储商品Id
      this.skuId = cartInfo.skuId
      // 修改isDelOne
      this.isDelOne = true
    },
    // 点击删除选中商品显示模态框并存储id到skuIdList
    showDialogByDelSelectCartInfo() {
      // 清空skuIdList 和 leftCartListInfo
      this.skuIdList = []
      this.leftCartListInfo = []
      // 模态框显示
      this.isShow = true
      // 存储选中商品ID
      this.cartInfoList.forEach((goods) => {
        if (goods.isChecked) {
          this.skuIdList.push(goods.skuId)
        } else {
          this.leftCartListInfo.push(goods)
        }
      })
      // 修改isDelOne
      this.isDelOne = false
    },
    // 点击确认删除商品
    async delCartInfo() {
      // if (this.isDelOne) {
      //   await reqDelOneShopCartInfo(this.skuId)
      //   // 重新发送请求渲染购物车数据
      //   this.getCartListData()
      // } else {
      //   await reqDelSelectCartInfo({ data: this.skuIdList })
      //   // 重新发送请求渲染购物车数据
      //   this.getCartListData()
      // }

      if (this.isDelOne) {
        await reqDelOneShopCartInfo(this.skuId)
        // 遍历数组渲染页面
        this.cartInfoList = this.cartInfoList.filter(
          (cartInfo) => cartInfo.skuId !== this.skuId
        )
      } else {
        await reqDelSelectCartInfo({ data: this.skuIdList })
        this.cartInfoList = this.leftCartListInfo
      }
      // 模态框隐藏
      this.isShow = false
    },
    // 点击修改多选框状态
    async checkCartInfoState(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked
      const res = await reqChangeShopCartInfoState(cartInfo.skuId, isChecked)
      // 更新服务器数据成功后，重新更新页面
      cartInfo.isChecked = isChecked
    },
  },
  mounted() {
    this.getCartListData()
  },
}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  .dialog-body {
    height: 120px;
    line-height: 60px;
  }
  .btn-footer {
    position: absolute;
    right: 40px;
    bottom: 20px;
    .btn {
      width: 62px;
      height: 32px;
      font-size: 14px;
      margin-left: 16px;
      border-width: 1px;
      border-radius: 10%;
      cursor: pointer;
      &.btn-primary {
        background-color: rgb(102, 177, 255);
        color: #fff;
      }
    }
  }
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
</style>
